package org.jwt.filter;

import com.google.gson.Gson;
import org.jwt.dto.ResultVO;
import org.jwt.utils.JwtUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author zqx
 * @date 2021-11-14
 */
@WebFilter("/api/*")
public class ZAuthFilter implements Filter {
    private static final String LOGIN = "login" ;
    public static final String TOKEN_HEADER = "Authorization";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //1.向下转型
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;


        String method = request.getMethod();
        if("OPTIONS".equals(method)) {
            filterChain.doFilter(request, response);
            return ;
        }

        //2.设置统一编码
        String requestURI = request.getRequestURI();
        if(requestURI.endsWith(LOGIN)) {
            //3.放行
            filterChain.doFilter(request, response);
            return;
        }

        String token = request.getHeader(TOKEN_HEADER);
        if(token==null || "".equals(token)) {
            responseView(response,"请先登录") ;
            return ;
        }

        try {
            JwtUtil.verify(token);

            String username = JwtUtil.getPayload(token, "username", String.class);
            if(username==null || username=="") {
                responseView(response,"解析token失败") ;
                return;
            }
            filterChain.doFilter(request, response);
        } catch (Exception e) {
            responseView(response,"会话已失效") ;
        }
    }

    @Override
    public void destroy() {

    }

    private void responseView(HttpServletResponse response, String message) throws IOException {
        ResultVO vo = new ResultVO();
        vo.setCode(401);
        vo.setMsg(message);
        response.setContentType("application/json;charset=utf-8");
        String json = new Gson().toJson(vo) ;
        PrintWriter out = response.getWriter();
        out.print(json) ;
        out.flush();
        out.close();
    }
}
